import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:orginone/config/theme/UIConfig.dart';
import 'package:orginone/components/XScaffold/XScaffold.dart';
import 'package:orginone/components/ChatSessionWidget/components/MessageListWidget/components/DetailItemWidget/DetailItemWidget.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/core/chat/message.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:scrollable_positioned_list/scrollable_positioned_list.dart';
import '../../../../../../../EntityWidget/common_fun.dart';
import 'BaseDetailWidget.dart';

///分组消息转发
class ForwardChatDetailWidget extends BaseDetailWidget {
  late final List<IMessage> msgBody;

  ForwardChatDetailWidget({
    super.key,
    required super.isSelf,
    required super.message,
    super.clipBehavior = Clip.hardEdge,
    super.padding = const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
    super.bgColor,
    super.constraints,
    super.isReply = false,
    super.chat,
  }) {
    msgBody = message.forward!;
  }

  @override
  Widget body(BuildContext context) {
    String showName = '';
    List<String> fromName = [];
    fromName.addAll(msgBody.map((e) => e.from.name).toSet().toList());

    if (fromName.length > 2) {
      showName = "群聊";
    } else if (fromName.length == 1) {
      showName = '${fromName[0]}的';
    } else {
      showName = '${fromName[0]}和${fromName[1]}的';
    }

    BoxConstraints boxConstraints =
        BoxConstraints(minWidth: 280.w, maxWidth: UIConfig.screenWidth - 110);
    Widget child = GestureDetector(
      onTap: () {
        onTap(context);
      },
      child: Container(
          constraints: boxConstraints,
          color: Colors.transparent,
          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Text(
              "$showName会话消息",
              style: XFonts.size22Black0W700,
            ),
            const Divider(),
            Container(
                constraints: boxConstraints,
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: msgBody
                        .sublist(0, min(3, msgBody.length))
                        .map((msg) => Text(getShowData(msg)))
                        .toList()))
          ])),
    );
    return child;
  }

  getShowData(IMessage msg) {
    String txtPin = '';
    if (msg.msgType == MessageType.text.label) {
      txtPin = '${msg.from.name}:${msg.msgBody}';
    } else if (msg.msgType == MessageType.file.label ||
        msg.msgType == MessageType.video.label) {
      FileItemShare fileItemShare =
          FileItemShare.fromJson(jsonDecode(msg.msgBody));
      txtPin = '${msg.from.name}:${fileItemShare.name}';
    } else {
      txtPin = '${msg.from.name}:[${msg.msgType}]';
    }
    return txtPin;
  }

  _item(IMessage messageItem) {
    Widget currentWidget = DetailItemWidget(
      msg: messageItem,
      chat: chat!,
      key: ObjectKey(messageItem.metadata),
    );
    var time = getChatTime(messageItem.createTime);
    var item = Column(children: [currentWidget]);
    item.children.insert(0, time);
    return item;
  }

  @override
  void onTap(BuildContext context) async {
    final ItemScrollController itemScrollController = ItemScrollController();
    Widget widget = ScrollablePositionedList.builder(
      padding: EdgeInsets.only(left: 10.w, right: 10.w),
      shrinkWrap: true,
      // key: controller.state.scrollKey,
      reverse: false,
      physics: const ClampingScrollPhysics(),
      itemScrollController: itemScrollController,
      addAutomaticKeepAlives: true,
      addRepaintBoundaries: true,
      itemCount: msgBody.length,
      itemBuilder: (BuildContext context, int index) {
        return _item(msgBody[index]);
      },
    );
    return showDialog(
        context: context,
        useSafeArea: false,
        builder: (context) {
          return XScaffold(
              titleName: '转发的聊天记录',
              backgroundColor: Colors.white,
              body: Container(
                  padding: EdgeInsets.only(
                      // top: UIConfig.safeTopHeight,
                      bottom: UIConfig.safeBottomHeight),
                  height: UIConfig.screenHeight,
                  child: widget));
        });
  }
}
